<?php
namespace Admin\Controller;

class CategoryController extends BaseController{

    public function index(){
    	$cate = M("category")->select();
    	$max = M("category")->max("id");

    	$this->assign("cate",json_encode($cate));
    	$this->assign("max",$max);

        $this->display();
    }

    public function del(){
    	if(IS_AJAX){
    		$id = I("post.id");
    		$res =M("category")->delete($id);
    		if($res){
    			$message=array(
    				"error"=>0,
    				"message"=>'删除成功',
    			);
    		}else{
    			$message=array(
    				"error"=>1,
    				"message"=>'删除失败',
    			);
    		}
    		$this->ajaxReturn($message);
    	}
    }

    //分类
    public function get_category($pid=0,$category = array()){
        $dingji=M("category")->where(array("pid"=>0))->select();//顶级分类


        foreach($dingji as $k=>$v){
            $category[] = $v;

            $category =$this->get_category($v["id"],$category);
        }
            return $category;


    }

    //新增或者修改数据库
    public function change(){
    	if(IS_AJAX){
    		$id = I("post.id");
    		//查询该id在数据库中是否存在，存在即修改，不存在即新增
    		$res= M("category")->where(array("id"=>$id))->find();
    		if(!empty($res)){
    			M("category")->where(array("id"=>$id))->save($_POST);
    			$message=array(
    				"error"=>0,
    				"message"=>'修改成功',

    			);
    		}else{
    			M("category")->add($_POST);
    			$message=array(
    				"error"=>0,
    				"message"=>'新增成功',
    			);
    		}
    		$this->ajaxReturn($message);
    	}
    }
}
?>